package org.nicocube.airain.utils.telnet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Collection;

public class NetworkConnection {

	private static final String DEFAULT_PROMPT = "> ";
	
    private Socket socket;
    private java.io.PrintWriter os;
    private java.io.BufferedReader in;
    private boolean connected = false;
    
	public NetworkConnection(Socket socket) throws IOException {
		this.socket = socket;
		this.os = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
		this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		this.connected = true;
		this.socket.setSoTimeout(40 * 1000);
	}

    public void disconnect() {
		if (connected) {
		    try {
		    	os.close();
		    }
		    catch (Exception ignore) {}
		    finally {
		    	os = null;
		    }
		    
		    try {
		    	in.close();
		    }
		    catch (Exception ignore) {}
		    finally {
		    	in = null;
		    }
		    
		    try {
		    	socket.close();
		    }
		    catch (Exception ignore) {}
		    finally {
		    	socket = null;
		    }
		    
		    connected = false;
		}
    }

    public void send(String cmd) {
    	os.print(cmd);
    	os.flush();
    }
    
    public void sendLine(String cmd) {
    	os.print(cmd + "\r\n");
    	os.flush();
    }

    public void sendLines(Collection<String> cmdSet) {
    	for (String cmd : cmdSet) {
    		os.print(cmd);	
    	}
    	os.flush();
    }

    public String readLine() throws IOException {
    	String cmd = in.readLine();
    	if (cmd == null) {
    		throw new IOException("reading null cmd");
    	}
    	return cmd;
    }	
	
    public String prompt() throws IOException {
    	send(DEFAULT_PROMPT);
    	return readLine();
    }
}
